from tkinter import *

def rollbacksql(sql_file):

    sql = open(sql_file, "r", encoding = "utf8")
    sqltxts = sql.readlines()

    UPDATE='UPDATE'
    DELETE='DELETE'

    sqlmeger=''

    for sqlsqltxt in sqltxts:
        if sqlsqltxt.__contains__(';'):
            sql = sqlsqltxt.split(';')
            #分号之前的语句
            s1 = sql[0]
            #分号之后的语句
            sss = sql[1]

            if s1.__contains__(UPDATE):
                #'UPDATE `yanghua0`.`sys_dictionary` SET `did`=1456185142115684354, `dname`='杨华', `dvalue`=100020, `type`='COUNTY_CODE' WHERE `did`=1456185142115684354 AND `dname`='34' AND `dvalue`=100020 AND `type`='COUNTY_CODE' LIMIT 1'
                s11 = s1.split('LIMIT')
                s12 = s11[0].split('SET')
                s13 = s12[1].split('WHERE')
                #重新组合拼接
                s2 = s12[0] +' SET '+s13[1] + ' WHERE ' +s13[0].replace(',',' AND ') +' LIMIT '+ s11[1]+sss
                sqlmeger += s2 +'\n'
            if s1.__contains__(DELETE):
                s11 = s1.replace('LIMIT 1','').split('WHERE')
                # 数据库和表名
                dbt = s11[0].replace('DELETE FROM', 'INSERT INTO')
                s12 = s11[1].split('AND')
                #keys
                keys="("
                #values
                values='VALUES ('
                for s in s12:
                    keys += s.split('=')[0]+','
                    values += s.split('=')[1]+','
                dbt += keys[0:len(keys)-1]+")"+values[0:len(values)-1]+") LIMIT 1;"+sss

                sqlmeger += dbt +'\n'
    return  sqlmeger


def writeSql():
    fileName = entry1.get().strip()
    sql_file = entry2.get().strip()

    with open('D:'+fileName+'.sql','w',encoding="utf8") as f:
        f.write(rollbacksql(sql_file))
    print('执行完毕')



if __name__ == '__main__':


    root = Tk()
    root.title('MySQL删改回滚,作者:杨二狗,输出文件在D盘')
    root.geometry('400x300+500+200')
    root.resizable(False, False)

    fileName = Label(root, text='输出文件名', font=('黑体', 18), fg='blue')
    fileName.grid()
    entry1 = Entry(root)

    entry1.grid(row=0, column=1)
    entry1.insert(0, "rollbackSQL")

    sql_file = Label(root, text='输出文件名', font=('黑体', 18), fg='blue')
    sql_file.grid()
    entry2 = Entry(root)
    entry2.grid(row=1, column=1)
    entry2.insert(0, "D:\mysql-bin.000027.sql")

    button = Button(root, text='转化', width=10, command=writeSql).grid(row=18, column=0)
    button2 = Button(root, text='退出', width=10, command=root.quit).grid(row=18, column=1)

    root.mainloop()